#include <iostream>
#include <memory>
#include <functional>

#include "Task.hpp"
#include "tcpserver.hpp"
#include "log.hpp"

Log log;

void default_on_message(std::function<std::string(std::string&)> On_func, std::shared_ptr<Connection> connection)
{
    log(Info, "on message, fd: %d, %s", connection->socket_fd(), connection->Inbuffer().c_str());
    
    while (true)
    {
        std::string response_str = On_func(connection->Inbuffer());
        if (response_str.empty())
            break;
        log(Info, "response str: %s", response_str.c_str());
        connection->Outbuffer() += response_str;
    }
    connection->_send_callback(connection);
}

int main()
{
    ServerCal cal;
    std::function<std::string(std::string&)> On_func = std::bind(&ServerCal::Handler, &cal, std::placeholders::_1);

    link_socket links;
    std::unique_ptr<Listener> listener(new Listener(8081));
    listener->init();

    // 更改tcpserver的运行时仅需传入不同的On_func
    std::unique_ptr<TcpServer> svr(new TcpServer(std::bind(default_on_message, On_func, std::placeholders::_1)));
    // tcpserver初始化
    svr->init();
    // tcpserver绑定监听套接字
    svr->add_connection(listener->socket_fd(), Epoller::EVENT_IN | Epoller::EVENT_ET, \
                        std::bind(&Listener::Accept, listener.get(), std::placeholders::_1), nullptr, \
                        std::bind(&link_socket::Except, &links, std::placeholders::_1));
    // tcpserver开始事件分配
    svr->start();

    return 0;
}